package net.niufei.study.cpatterns.readwritelock;

public class ReadWriteLock {

	private int iReader = 0, iWriter = 0;
	private int iWaitWriter = 0;
	private boolean readyWrite = false;
	
	public synchronized void readLock() throws InterruptedException {
		while(iWriter > 0 || (readyWrite && iWaitWriter > 0)) {
			wait();
		}
		iReader++;
	}
	
	public synchronized void readUnlock() {
		iReader--;
		readyWrite = true;
		notifyAll();
	}
	
	public synchronized void writeLock() throws InterruptedException {
		iWaitWriter++;
		try {
			while(iReader > 0 || iWriter > 0) {
				wait();
			}
		}
		finally {
			iWaitWriter--;
		}
		iWriter++;
	}
	
	public synchronized void writeUnlock() {
		iWriter--;
		readyWrite = false;
		notifyAll();
	}
}
